package edu.ufl.cise.sanitas.client;

import android.app.AlertDialog;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.DialogInterface.OnClickListener;
import android.database.Cursor;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.SimpleCursorAdapter;
import edu.ufl.cise.sanitas.client.proxy.Proxy;
import edu.ufl.cise.sanitas.types.comm.FetchAllNewsfeedResponse;
import edu.ufl.cise.sanitas.types.comm.Response;
import edu.ufl.cise.sanitas.types.data.Condition;
import edu.ufl.cise.sanitas.types.data.Feed;

public class Newsfeed extends ListActivity {
	
	private static final String LOG_TAG = "sanitas.client.Newsfeed";
	
	private static final int NEWPOST_ID = Menu.FIRST;
	private static final int DAILYLOG_ID = Menu.FIRST + 1;
	private static final int UPDATEFEEDS_ID = Menu.FIRST + 2;
	private static final int PROFILE_ID = Menu.FIRST + 3;
	private static final int EXIT_ID = Menu.FIRST + 4;
	private static final int ACTIVITY_SIGNIN = 0;
	private static final int ACTIVITY_NEWPOST = 1;
	private static final int ACTIVITY_DAILYLOG = 2;
	private static final int ACTIVITY_MODE = 3;
	private static final int ACTIVITY_PROFILE = 4;
	private Proxy mProxy;
	private Context mCtx;
	
	private ProgressDialog pd;
	private AlertDialog ad;
	

	private Handler newFeedHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			Feed newFeed = (Feed) msg.obj;
			
			Condition[] condList = Proxy.getConditionList();
			boolean flag = false;
			if (newFeed.getTheme().equals("general")) flag = true;
			else 
			{
				for (Condition c : condList) {
					if (c.getConditionName().equals(newFeed.getTheme())) {
						flag = true;
						break;
					}
				}
			}
			if (flag) {
				mProxy.insertFeedToFeeds(newFeed);
				fillData();
			}
			
		}
	};
	
	private Handler updateNewsfeedHandler = new Handler() {
		
		@Override
		public void handleMessage(Message msg) {
			
			Response response = (Response) msg.obj;
			
			switch (response.getStatus()) {
			case SUCCESS:
				mProxy.updateAllNewsfeed(((FetchAllNewsfeedResponse) response).getNewsFeed());
				fillData();
				break;
			case TIMEOUT:
			case FAIL:
				AlertDialog.Builder timeoutBuilder = new AlertDialog.Builder(mCtx);
				timeoutBuilder.setTitle("Newsfeed")
						.setMessage("Newsfeed fetching failed. Please try again later...")
						.setPositiveButton("Continue", new OnClickListener() {

							@Override
							public void onClick(DialogInterface dialog,
									int which) {
								ad.dismiss();
							}
						});
				ad = timeoutBuilder.create();
				ad.show();
				break;
			}
			
			pd.dismiss();
		}
		
	};
	
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
        Log.i(LOG_TAG, "SanitasLink Started!");
        
        setContentView(R.layout.newsfeed);
        mProxy = Proxy.getInstance(this, newFeedHandler);
        mProxy.setUpdateNewsfeedHandler(updateNewsfeedHandler);
        mProxy.open();
        mCtx = this;
        
        login();
    }
    
    @Override
    public void onDestroy() {
    	super.onDestroy();
    	mProxy.close();
    	Log.i(LOG_TAG, "SanitasLink Destoried!");
    }

	private void login() {
		Intent i = new Intent(this, Launcher.class);
		startActivityForResult(i, ACTIVITY_SIGNIN);
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
//		Bundle extras = data.getExtras();
		switch (requestCode) {
		case ACTIVITY_SIGNIN:
			switch (resultCode) {
			case RESULT_CANCELED:
				login();
				break;
			case RESULT_OK:
				pd = ProgressDialog.show(this, "Newsfeed", "Loading...");
				mProxy.requestNewsfeed();
			}
			break;
		case ACTIVITY_NEWPOST:
			break;
		case ACTIVITY_MODE:
			break;
		case ACTIVITY_PROFILE:
			switch (resultCode) {
			case RESULT_CANCELED:
				login();
				break;
			case RESULT_OK:
				pd = ProgressDialog.show(this, "Newsfeed", "Loading...");
				mProxy.requestNewsfeed();
				break;
			}
			break;
		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		boolean result = super.onCreateOptionsMenu(menu);
		menu.add(0, NEWPOST_ID, 0, R.string.menu_newpost);
//		menu.add(0, DAILYLOG_ID, 0, R.string.menu_dailylog);
		menu.add(0, UPDATEFEEDS_ID, 0, R.string.menu_update_feeds);
		menu.add(0, PROFILE_ID, 0, R.string.menu_profile);
		menu.add(0, EXIT_ID, 0, R.string.menu_exit);
		return result;
	}

	@Override
	public boolean onMenuItemSelected(int featureId, MenuItem item) {
		switch (item.getItemId()) {
		case NEWPOST_ID:
			createNewPost();
			return true;
		case DAILYLOG_ID:
			execDailyLog();
			return true;
		case UPDATEFEEDS_ID:
			execUpdateFeeds();
			return true;
		case PROFILE_ID:
			execProfile();
			return true;
		case EXIT_ID:
			this.finish();
			return true;
		}
		return super.onMenuItemSelected(featureId, item);
	}

	private void execProfile() {
		Intent i = new Intent(this, Profile.class);
		startActivityForResult(i, ACTIVITY_PROFILE);
	}

	private void execUpdateFeeds() {
//		Intent i = new Intent(this, Mode.class);
//		startActivityForResult(i, ACTIVITY_MODE);
		pd = ProgressDialog.show(this, "Newsfeed", "Loading...");
		mProxy.requestNewsfeed(); 
	}

	private void execDailyLog() {
		Intent i = new Intent(this, DailyLog.class);
		startActivityForResult(i, ACTIVITY_DAILYLOG);
	}
	
	private void createNewPost() {
		Intent i = new Intent(this, NewPostEdit.class);
		startActivityForResult(i, ACTIVITY_NEWPOST);
	}
    
	private void fillData() {
		Cursor c = mProxy.fetchAllFeeds();
		startManagingCursor(c);
		
		String[] from = new String[] { Proxy.KEY_FEEDS_USERNAME, Proxy.KEY_FEEDS_TIME, Proxy.KEY_FEEDS_CONTENT, Proxy.KEY_FEEDS_THEME };
		int[] to = new int[] { R.id.feed_row_name, R.id.feed_row_time, R.id.feed_row_content, R.id.feed_row_theme };
		
		SimpleCursorAdapter feeds = new SimpleCursorAdapter(this, R.layout.feed_row, c, from, to);
		setListAdapter(feeds);
	}
    
}